package com.wei.chatroom.controller;

import com.wei.chatroom.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @projectName: chatroom
 * @package: com.wei.chatroom.controller
 * @className: MessageSessionController
 * @author: weiJiang
 * @description: 管理会话的类
 * @date: 2025/9/23 下午2:04
 * @version: 1.0
 */

@RestController
public class MessageSessionController {

    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Autowired
    private MessageMapper messageMapper;

    /**
     * @param :
     * @return Object
     * @author weiJiang
     * @description 构造MessageSession对象数组
     * @date 2025/9/23 下午2:06
     */
    @GetMapping("/sessionList")
    public Object getMessageSessionList(HttpServletRequest req){

        List<MessageSession> messageSessionList=new ArrayList<>();
        //获取当前用户userId,(session)
        HttpSession session=req.getSession(false);

        if(session==null){
            System.out.println("getMessageSession方法获取session失败");
            return messageSessionList;
        }

        User user=(User) session.getAttribute("user");

        if(user==null){
            System.out.println("getMessageSession方法获取user失败");
            return messageSessionList;
        }


        //根据id查询看有哪些会话

        List<Integer> sessionIdList = messageSessionMapper.getSessionIdByUserId(user.getUserId());


        for(int sessionId :sessionIdList){
            //遍历查出的会话id，查询好友都有哪些
            MessageSession messageSession=new MessageSession();
            List<Friend> friends=messageSessionMapper.getFriendsBySessionId(sessionId, user.getUserId());
            messageSession.setSessionId(sessionId);
            messageSession.setFriends(friends);
            //以及每个会话的最后消息
            String lastMessage=messageMapper.getLastMessageBySessionId(sessionId);
            //有可能没有消息：新会话来不及发
            if(lastMessage==null){
                messageSession.setLastMessage("");
            } else{
                messageSession.setLastMessage(lastMessage);
            }

            messageSessionList.add(messageSession);
        }

        return messageSessionList;

    }

    //只要后端方法有同名参数 Integer toUserId，Spring 就会自动从 URL 参数或请求体中找 toUserId 并赋值
    //这里需要引入事务，要么全插入，发生异常了一个都别想插入(保证原子性)
    @PostMapping("/session")
    @Transactional
    public Object addMessageSession(Integer toUserId, @SessionAttribute("user") User user){//更先进的获取当前user

        HashMap<String,Integer> resp=new HashMap<>();
        //useGeneratedKeys="true" + keyProperty="sessionId"
        //这两个语句让传入对象自动获得了sessionId,其它的都为null
        MessageSession messageSession=new MessageSession();
        messageSessionMapper.addMessageSession(messageSession);

        //当前用户插入
        MessageSessionUserItem item1=new MessageSessionUserItem();
        item1.setSessionId(messageSession.getSessionId());
        item1.setUserId(user.getUserId());
        messageSessionMapper.addMessageSessionUser(item1);

        //朋友插入
        MessageSessionUserItem item2=new MessageSessionUserItem();
        item2.setSessionId(messageSession.getSessionId());
        item2.setUserId(toUserId);
        messageSessionMapper.addMessageSessionUser(item2);

        System.out.println("新增会话成功");
        resp.put("sessionId",messageSession.getSessionId());
        //返回的对象是普通对象或者MAP都行，jackson都能处理
        return resp;
        //返回sessionId
    }
}
